const klineService = require('../services/kline');

// 获取K线数据
exports.getKlineData = async (req, res) => {
  try {
    const { symbol, interval, startTime, endTime } = req.query;
    const klineData = await klineService.getKlineData(symbol, interval, startTime, endTime);
    res.json(klineData);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 获取交易对列表
exports.getSymbols = async (req, res) => {
  try {
    const symbols = await klineService.getSymbols();
    res.json(symbols);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 获取实时K线数据
exports.getRealtimeKline = async (req, res) => {
  try {
    const { symbol, interval } = req.query;
    // 设置响应头，保持连接打开
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    // 发送实时数据
    const sendRealtimeData = async () => {
      try {
        const data = await klineService.getLatestKline(symbol, interval);
        res.write(`data: ${JSON.stringify(data)}

`);
        // 继续发送
        setTimeout(sendRealtimeData, 5000); // 每5秒发送一次
      } catch (error) {
        res.write(`error: ${error.message}

`);
        setTimeout(sendRealtimeData, 5000);
      }
    };

    // 开始发送数据
    sendRealtimeData();

    // 监听连接关闭
    req.on('close', () => {
      console.log('客户端断开连接');
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};